package cn.com.headfree.dictionary.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gta.edu.sdk.base.controller.BaseController;
import com.gta.edu.sdk.common.constant.Constant;
import com.gta.edu.sdk.common.dto.LoginUserInfo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.common.dto.TreeDto;
import com.gta.edu.sdk.log.annotation.OperationLog;
import com.gta.edu.sdk.log.contant.LogType;
import com.gta.edu.sdk.log.contant.OperationType;
import com.gta.edu.sdk.log.entity.TSysLogInfo;
import com.gta.edu.sdk.util.CommUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.initdata.InitCacheData;
import cn.com.headfree.dictionary.entity.TCommonDictionary;
import cn.com.headfree.dictionary.service.IDictionaryService;
import net.sf.json.JSONObject;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/dictionaryManage", produces = "application/json;charset=UTF-8")
public class DictionaryManageController extends BaseController {

    private static final Logger log = LogManager.getLogger(DictionaryManageController.class);
    @Autowired
    private IDictionaryService dictionaryService;

    /**
     * 分页查询字典数据-根据父节点id查询子节点,用于表格展示
     *
     * @param pId
     * @param page
     */
    @OperationLog(detail="分页查询字典数据-根据父节点id查询子节点,用于表格展示",operationType=OperationType.SELECT)
    @RequestMapping("/findPageDictionaryByPId")
    public JSONObject findPageDictionaryByPId(String pId, String sysCode, String name, Page<TCommonDictionary> page) {
        JSONObject pageJSONData = null;
        try {
            TCommonDictionary parentDic = dictionaryService.get(TCommonDictionary.class, pId);
            dictionaryService.findPageDictionaryByPId(pId, sysCode,name, page);
            List<TCommonDictionary> list = page.getResult();
            //获取父节点的名称
            if (parentDic != null) {
                if (list != null && list.size() > 0) {
                    TCommonDictionary vo = null;
                    for (int i = 0; i < list.size(); i++) {
                        vo = list.get(i);
                        vo.setpName(parentDic.getName());
                    }
                }
            } else {
                if (list != null && list.size() > 0) {
                    TCommonDictionary vo = null;
                    for (int i = 0; i < list.size(); i++) {
                        vo = list.get(i);
                        vo.setpName("根节点");
                    }
                }
            }
            pageJSONData = CommUtil.getPageJSONData(page, true);
        } catch (Exception e) {
            log.error("根据父节点的值，或者所有子节点的记录数据失败，原因：后端出现异常！", e);
        }
        return pageJSONData;
    }
    
    @RequestMapping("/test")
    public ResultData testAnno(String mobile) {
    	long startTime = System.currentTimeMillis();
    	ResultData result = new ResultData();
    	TSysLogInfo log = new TSysLogInfo();
    	try {
    	log.setLogContent("业务操作说明");
		log.setOpType(OperationType.SELECT.getValue());
		log.setResult(1);
		log.setOpEntity("参数脱敏的形式写入");
    	} catch (Exception e) {
    		log.setResult(0);
    		result.setSuccess(false);
    	}
    	long endTime = System.currentTimeMillis();
    	log.setExeTime(endTime-startTime);
    	this.writeOperationLog(log);
    	return result;
    }

    /**
     * 根据父节点查询树形结构
     *
     * @param pId
     * @return
     */
    @GetMapping("/dictTreeList")
    public List<TreeDto> dictTreeList(HttpServletRequest request, String pId, String sysCode) {
        try {
            WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            TreeDto dto = dictionaryService.dictTreeList(pId, sysCode, app);
            List<TreeDto> list = new ArrayList<>(1);
            list.add(dto);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询系统字典数据,父节点值为sys_code对应的数据
     *
     * @param parentValue
     * @return
     */
    @OperationLog(detail="公共组件数据字典查询",operationType=OperationType.SELECT)
    @GetMapping("/listSys")
    public ResultData getAllByParentValue(String parentValue) {
        ResultData result = new ResultData();
        try {
            List<TCommonDictionary> dicts = dictionaryService.getAllByParentValue(parentValue);
            result.setData(dicts);
        } catch (Exception e) {
        	String errorMsg = "根据父节点的值，或者所有子节点的记录数据失败，原因：后端出现异常！";
            log.error(errorMsg, e);
            result.setSuccess(false);
            result.setData(errorMsg);
        }
        return result;
    }

    /**
     * 根据字典id查询字典信息,用于增改时回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/findDictInfoById")
    public ResultData findDictInfoById(String id) {
        if (StringUtil.isNullOrEmpty(id)) {
            log.info("根据id查询字典信息失败，原因：传递的节点id的值为空！");
            return null;
        }
        ResultData result = new ResultData();
        try {
            //根据id查询字典
            TCommonDictionary dic = dictionaryService.get(TCommonDictionary.class, id);
            result.setData(dic);
        } catch (Exception e) {
            log.info("根据id获取字典数据失败，原因：后端出现异常！", e);
            result.setSuccess(false);
            result.setErrorMsg("根据id获取字典数据失败，原因：后端出现异常！");
        }
        return result;
    }

    /**
     * 保存字典
     *
     * @param tCommonDictionary
     * @return
     */
//    @OperationLog(detail="公共组件数据字典中数据进行添加或者修改操作",operationType=OperationType.UPDATE)
    @RequestMapping("/save")
    public ResultData saveOrUpdate(HttpServletRequest request, TCommonDictionary tCommonDictionary) {
        ResultData result = new ResultData();
        long startTime = System.currentTimeMillis();
    	TSysLogInfo sysLog = new TSysLogInfo();
    	sysLog.setLogContent("数据字典添加/更新操作");
    	sysLog.setResult(1);
    	sysLog.setOpEntity("参数：" + JSONObject.fromObject(tCommonDictionary).toString());
        try {
            //获取人员信息
            LoginUserInfo userInfo = this.getLongUserInfo();
            if (StringUtil.isNullOrEmpty(tCommonDictionary.getId())) {
                //如果传入的id为空,则说明是新增,设置创建时间
                tCommonDictionary.setId(null);
                tCommonDictionary.setCreaterId(userInfo.getIscUserId());
                tCommonDictionary.setCreaterName(userInfo.getIscAdCode());
                tCommonDictionary.setCreateTime(new Date());
                sysLog.setOpType(OperationType.INSERT.getValue());
            } else {
            	sysLog.setOpType(OperationType.UPDATE.getValue());
            }
            //设置更新时间
            tCommonDictionary.setUpdaterId(userInfo.getIscUserId());
            tCommonDictionary.setUpdaterName(userInfo.getIscAdCode());
            tCommonDictionary.setUpdateTime(new Date());
            //保存数据
            dictionaryService.saveOrUpdate(tCommonDictionary);
            this.dictionaryService.cleanCache();
            //保存成功后刷新缓存
            WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            InitCacheData.getInstance().initData(app);
            result.setData(Constant.SAVE_SUCCESS);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setData(Constant.SAVE_UN_SUCCESS);
            log.error("保存失败", e);
            sysLog.setResult(0);
        } finally {
        	long endTime = System.currentTimeMillis();
        	sysLog.setExeTime(endTime-startTime);
        	this.writeOperationLog(sysLog);
        }
        return result;
    }

    /**
     * 删除字典
     *
     * @param deleteIds
     * @return
     */
    @OperationLog(detail="公共组件数据字典中数据进行删除操作",operationType=OperationType.DELETE)
    @RequestMapping("/delete")
    public ResultData delete(HttpServletRequest request, String[] deleteIds) {
        ResultData result = new ResultData();
        try {
            //逻辑删除,讲delSign置为1
            if (deleteIds != null && deleteIds.length > 0) {
                this.dictionaryService.removeData(deleteIds);
                //清空缓存
                WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
                InitCacheData.getInstance().initData(app);
                this.dictionaryService.cleanCache();
            }
            result.setData(Constant.DEL_SUCCESS);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setData(Constant.DEL_UN_SUCCESS);
            result.setErrorMsg("delete error");
            log.error("字典删除失败!!!", e);
        }
        return result;
    }

}
